package com.zkas.munqr.camera;

import java.io.IOException;

import com.zkas.munqr.TypeSource;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;

public class CameraManager {
	private static final String TAG = CameraManager.class.getSimpleName();
	private static final int MIN_FRAME_WIDTH = 240;
	private static final int MIN_FRAME_HEIGHT = 240;
	private static final int MAX_FRAME_WIDTH = 600;
	private static final int MAX_FRAME_HEIGHT = 400;

	private final CameraConfigurationManager configManager;
	private final Context context;
	private Camera camera;
	private boolean previewing;
	private Rect framingRect;
	private Rect framingRectInPreview;
	private boolean initialized;
	private AutoFocusManager autoFocusManager;
	private TypeSource mode;

	private final PreviewCallback previewCallback;

	public CameraManager(Context context) {
		this.context = context;
		this.configManager = new CameraConfigurationManager(context);
		mode = TypeSource.QR;
		previewCallback = new PreviewCallback(configManager);
	}

	public synchronized void openDriver(SurfaceHolder holder)
			throws IOException {
		Camera theCamera = camera;
		if (theCamera == null) {
			theCamera = Camera.open(0);
			if (theCamera == null) {
				theCamera = Camera.open(1);
				if (theCamera == null) {
					throw new IOException();
				}
			}
			camera = theCamera;
		}
		theCamera.setPreviewDisplay(holder);

		if (!initialized) {
			initialized = true;
			configManager.initFromCameraParameters(theCamera);
		}

		Camera.Parameters parameters = theCamera.getParameters();
		String parametersFlattened = parameters == null ? null : parameters
				.flatten(); // Save these, temporarily
		try {
			configManager.setDesiredCameraParameters(theCamera, false);
		} catch (RuntimeException re) {
			// Driver failed
			Log.w(TAG,
					"Camera rejected parameters. Setting only minimal safe-mode parameters");
			Log.i(TAG, "Resetting to saved camera params: "
					+ parametersFlattened);
			// Reset:
			if (parametersFlattened != null) {
				parameters = theCamera.getParameters();
				parameters.unflatten(parametersFlattened);
				try {
					theCamera.setParameters(parameters);
					configManager.setDesiredCameraParameters(theCamera, true);
				} catch (RuntimeException re2) {
					// Well, darn. Give up
					Log.w(TAG,
							"Camera rejected even safe-mode parameters! No configuration");
				}
			}
		}

	}

	public synchronized boolean isOpen() {
		return camera != null;
	}

	/**
	 * Closes the camera driver if still in use.
	 */
	public synchronized void closeDriver() {
		if (camera != null) {
			camera.release();
			camera = null;
			// Make sure to clear these each time we close the camera, so that
			// any scanning rect
			// requested by intent is forgotten.
			// framingRect = null;
			// framingRectInPreview = null;
		}
	}

	/**
	 * Asks the camera hardware to begin drawing preview frames to the screen.
	 */
	public synchronized void startPreview() {
		Camera theCamera = camera;
		if (theCamera != null && !previewing) {
			theCamera.startPreview();
			previewing = true;
			autoFocusManager = new AutoFocusManager(context, camera);
		}
	}

	/**
	 * Tells the camera to stop drawing preview frames.
	 */
	public synchronized void stopPreview() {
		if (autoFocusManager != null) {
			autoFocusManager.stop();
			autoFocusManager = null;
		}
		if (camera != null && previewing) {
			camera.stopPreview();
			previewCallback.setHandler(null, 0);
			previewing = false;
		}
	}

	public TypeSource getMode() {
		return mode;
	}

	public void setMode(TypeSource mode) {
		this.mode = mode;
	}

	public void resetFramingRect() {
		framingRect = null;
		framingRectInPreview = null;
	}

	public synchronized void requestPreviewFrame(Handler handler, int message) {
		Camera theCamera = camera;
		if (theCamera != null && previewing) {
			previewCallback.setHandler(handler, message);
			theCamera.setOneShotPreviewCallback(previewCallback);
		}
	}

	public Rect getFramingRect() {
		if (framingRect == null) {
			if (camera == null) {
				return null;
			}
			Point screenResolution = configManager.getScreenResolution();
			if (screenResolution == null) {
				// Called early, before init even finished
				return null;
			}

			int width = 0;
			int height = 0;
			int leftOffset = 0;
			int topOffset = 0;

			switch (mode) {
			case CUIT:
				width = screenResolution.x;
				height = (int) (width * 0.25);
				leftOffset = 0;
				topOffset = 0;

				break;
			case QR:
				width = screenResolution.x * 3 / 4;
				if (width < MIN_FRAME_WIDTH) {
					width = MIN_FRAME_WIDTH;
				} else if (width > MAX_FRAME_WIDTH) {
					width = MAX_FRAME_WIDTH;
				}
				height = screenResolution.y * 3 / 4;
				if (height < MIN_FRAME_HEIGHT) {
					height = MIN_FRAME_HEIGHT;
				} else if (height > MAX_FRAME_HEIGHT) {
					height = MAX_FRAME_HEIGHT;
				}
				leftOffset = (screenResolution.x - width) / 2;
				topOffset = (screenResolution.y - height) / 2;

				break;

			default:
				break;
			}

			framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
					topOffset + height);
			Log.d(TAG, "Calculated framing rect: " + framingRect);
		}
		return framingRect;
	}

	public synchronized Rect getFramingRectInPreview() {
		if (framingRectInPreview == null) {
			Rect framingRect = getFramingRect();
			if (framingRect == null) {
				return null;
			}
			Rect rect = new Rect(framingRect);
			Point cameraResolution = configManager.getCameraResolution();
			Point screenResolution = configManager.getScreenResolution();
			if (cameraResolution == null || screenResolution == null) {
				// Called early, before init even finished
				return null;
			}
			rect.left = rect.left * cameraResolution.x / screenResolution.x;
			rect.right = rect.right * cameraResolution.x / screenResolution.x;
			rect.top = rect.top * cameraResolution.y / screenResolution.y;
			rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
			framingRectInPreview = rect;
		}
		return framingRectInPreview;
	}

	public void takePicture(android.hardware.Camera.PreviewCallback mPicture) {
		camera.setOneShotPreviewCallback(mPicture);
	}

	public void takePicture(PictureCallback cPicture) {
		camera.takePicture(null, null, cPicture);
	}

	public int getPreviewFormat() {
		return camera.getParameters().getPreviewFormat();
	}

	public Size getPreviewSize() {
		return camera.getParameters().getPreviewSize();
	}
}
